package com.aly.beanValidate.core.validator.impl;

import com.alibaba.fastjson.JSONObject;
import com.aly.beanValidate.core.BeanDefinition;
import com.aly.beanValidate.core.FieldDefinition;
import com.aly.beanValidate.core.GlobalConfigs;
import com.aly.beanValidate.core.validator.CheckValidator;
import com.aly.beanValidate.core.validator.Name;
import com.aly.beanValidate.i.BeanInfo;
import com.aly.beanValidate.i.FileInfo;
import com.aly.beanValidate.i.FileInfos;
import org.dom4j.Element;

@Name("JsonNeedField")
public class JsonNeedFieldValidator extends CheckValidator {
    private final BeanDefinition beanDefinition;

    JsonNeedFieldValidator(Element element, GlobalConfigs globalConfigs) throws Exception {
        super(element, globalConfigs);
        beanDefinition = new BeanDefinition("", element, globalConfigs);
    }

    @Override
    public StringBuffer doValidate(FieldDefinition field, Object val, BeanInfo bean, FileInfo fileInfo, FileInfos fileInfos) {
        if (val instanceof JSONObject) {
            StringBuffer sb = beanDefinition.validate(((JSONObject) val)::getString, fileInfo, fileInfos);
            if (sb.length() > 0) {
                sb.insert(0, "JsonNeedField");
            }
            return sb;
        }
        return null;
    }
}
